package com.lanou.musicbox.adapter.seekmusic;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.musicbox.R;
import com.lanou.musicbox.bean.Single;
import com.lanou.musicbox.custom.Events;
import com.lanou.musicbox.download.CommonProgressDialog;
import com.lanou.musicbox.entity.Entity;
import com.lanou.musicbox.utils.MyConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by 赵宝龙 on 15/10/26.
 * 搜索_单曲页面Adapter
 */
public class EnterTheSeekMusic_SingleAdapter extends BaseExpandableListAdapter {
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 200) {
                commonProgressDialog.dismiss();
                Log.i("Sysout", "handleMessage_200");
            }
            return false;
        }
    });
    //group的内容
    private List<Single.DataEntity> data;
    private Context mContext;
    private String[] quality;
    private CommonProgressDialog commonProgressDialog;
    private List<Single.DataEntity.AuditionListEntity> listSong;
    private String song_link;
    private String url;
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");

    public EnterTheSeekMusic_SingleAdapter(List<Single.DataEntity> data, Context mContext) {
        this.mContext = mContext;
        this.data = data;
        notifyDataSetChanged();
        initdata();
        QQShare();
    }

    private void initdata() {
        UMSsoHandler qqSsoHandler = new UMQQSsoHandler((Activity) mContext, "100424468", "c7394704798a158208a74ab60104f0ba");
        qqSsoHandler.addToSocialSDK();
        //参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler((Activity) mContext, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }


    //child
    @Override
    public int getChildrenCount(int groupPosition) {
        return 1;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(final int groupPosition, final int position, boolean isLastChild, View convertView, ViewGroup parent) {
        ViewHolderOne holderOne = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.singlesong_content_child, null);
            holderOne = new ViewHolderOne();
            holderOne.musicDownload = (TextView) convertView.findViewById(R.id.music_download);
            holderOne.musicEnjoy = (TextView) convertView.findViewById(R.id.music_enjoy);
            holderOne.musicCollection = (TextView) convertView.findViewById(R.id.music_collection);
            holderOne.music_play = (TextView) convertView.findViewById(R.id.music_play);
            convertView.setTag(holderOne);
        } else {
            holderOne = (ViewHolderOne) convertView.getTag();
        }

        //对收藏进行监听
        holderOne.musicCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(mContext, "点击了收藏", Toast.LENGTH_SHORT).show();
            }
        });
        //对下载进行监听
        holderOne.musicDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("ZZZZZZZ", "------------------" + groupPosition);
                DownloadDialog(groupPosition);
            }
        });
        //对分享进行监听
        holderOne.musicEnjoy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                // 是否只有已登录用户才能打开分享选择页
                mController.openShare((Activity) mContext, false);
                Toast.makeText(mContext, "点击了分享", Toast.LENGTH_SHORT).show();
            }
        });
        //对播放进行监听
        holderOne.music_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listSong = data.get(groupPosition).getAuditionList();
                List<Entity> songsInfos = new ArrayList<>();
                Log.e("SSSSSS", "=============" + groupPosition);
                if (listSong != null && listSong.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        Entity netSongs = new Entity();

                        if (data.get(i).getAuditionList() != null && data.get(i).getAuditionList().size() > 1) {
                            song_link = data.get(i).getAuditionList().get(1).getUrl();
                        } else if (data.get(i).getAuditionList() != null && data.get(i).getAuditionList().size() == 1) {
                            song_link = data.get(i).getAuditionList().get(0).getUrl();
                        } else {
                            song_link = "";
                        }

                        String title = data.get(i).getName();
                        String author = data.get(i).getSingerName();
                        netSongs.setUrl(song_link);
//                            netSongs.setSmall_pic(bg_img);
//                            netSongs.setBig_pic(bg_img);
                        netSongs.setTitle(title);

                        netSongs.setArtist(author);
                        netSongs.setItem_id(groupPosition);
                        songsInfos.add(i, netSongs);
                    }
                    String whatMusic = "天天动听";
                    Events.MusicInfoEvent musicInfoEvent = new Events.MusicInfoEvent();
                    musicInfoEvent.setMp3Infos(songsInfos, whatMusic);
                    EventBus.getDefault().post(musicInfoEvent);
                } else {
                    Toast.makeText(mContext, "这首歌没有授权,我也无能为力哦!", Toast.LENGTH_SHORT).show();
                }


            }
        });
        return convertView;
    }

    //group
    @Override
    public int getGroupCount() {
        return data != null && data.size() > 0 ? data.size() : 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return data != null && data.size() > 0 ? data.get(groupPosition) : null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.entertheseekmusic_single_item, null);
            holder = new ViewHolder();
            holder.songListTime = (TextView) convertView.findViewById(R.id.song_list_time);
            holder.songTitle = (TextView) convertView.findViewById(R.id.song_title);
            holder.songSinger = (TextView) convertView.findViewById(R.id.song_singer);
            holder.songFivortNum = (TextView) convertView.findViewById(R.id.song_fivort_num);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Single.DataEntity dataEntity = (Single.DataEntity) getGroup(groupPosition);

        if (dataEntity != null) {
            holder.songTitle.setText(dataEntity.getName());
            holder.songFivortNum.setText(dataEntity.getFavorites() + "");
            holder.songSinger.setText(dataEntity.getSingerName());
            holder.songListTime.setText(groupPosition + 1 + "");
        }

        return convertView;
    }


    @Override
    public boolean hasStableIds() {
        return false;
    }

    //
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'singlesong_content_child.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'singlesong_content.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */
    static class ViewHolder {
        private TextView songListTime, songTitle, songSinger, songFivortNum;
    }

    static class ViewHolderOne {
        private TextView musicDownload, musicEnjoy, musicCollection, music_play;
    }

    //quality = {};

    /**
     * 点击下载弹出对话框
     */
    private void DownloadDialog(final int position) {
        final List<Single.DataEntity.AuditionListEntity> entity = data.get(position).getAuditionList();
        //数组初始化时一定要定义它的长度
        quality = new String[entity.size()];
        //获取小数点后两位的方法
        DecimalFormat df = new DecimalFormat("0.00");
        for (int i = 0; i < entity.size(); i++) {
            String str = entity.get(i).getTypeDescription();
            double size = entity.get(i).getSize();
            Log.i("tttttt", str);

            quality[i] = str + df.format(size / 1024000) + "M";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("请选择下载品质");
        builder.setItems(quality, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(mContext, entity.get(which).getTypeDescription() + "点击了下载", Toast.LENGTH_SHORT).show();
                url = entity.get(which).getUrl();
                String singerName = data.get(position).getSingerName();
                String title = data.get(position).getName();
                int size = entity.get(which).getSize();

                MyConfig.putSharePre(mContext, "url", "url", url);
                MyConfig.putSharePre(mContext, "singerName", "singerName", singerName);
                MyConfig.putSharePre(mContext, "title", "name", title);
                MyConfig.putSharePre(mContext, "size", "size", size);

                // 下载
                commonProgressDialog = new CommonProgressDialog(mContext, handler);
                commonProgressDialog.download(url, new File("/mnt/sdcard/Download/"));
                commonProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                commonProgressDialog.show();
                commonProgressDialog.setMax(size);
                commonProgressDialog.setName(title, singerName);

                Log.e("ZBL", "---->" + url + size);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
//设置分享文字
        qqShareContent.setShareContent("第一次给你分享东西，好好看");
//设置分享title
        qqShareContent.setTitle("不是吓唬你");
////设置分享图片
//        qqShareContent.setShareImage(new UMImage(getActivity(), R.drawable.icon));
//设置点击分享内容的跳转链接
        qqShareContent.setTargetUrl(url);
        mController.setShareMedia(qqShareContent);

        QZoneShareContent qzone = new QZoneShareContent();
//设置分享文字
        qzone.setShareContent("第一次给你分享东西，好好看");
//设置点击消息的跳转URL
        qzone.setTargetUrl(url);
//设置分享内容的标题
        qzone.setTitle("不是吓唬你");
////设置分享图片
//        qzone.setShareImage(urlImage);
        mController.setShareMedia(qzone);

    }

}
